#include "kvdb.h"
  
CKvdb::CKvdb()
{  
	db = NULL;
}

CKvdb::~CKvdb()
{  
  if(NULL != db)
  {
    delete db;
    db = NULL;
  }
  if(NULL != options.block_cache)
  {
    delete options.block_cache;
    options.block_cache = NULL;
  }
}

int32_t CKvdb::init(const char* szName)
{
  if (NULL == szName)
  {
    return -1;
  }
	options.block_cache = leveldb::NewLRUCache(50*1024*1024);
	options.create_if_missing = true;
	write_opt.sync = false;
	read_opt.fill_cache = true;

	leveldb::Status s = leveldb::DB::Open(options, szName, &db);
	if(s.ok())
  {
    return 0;
  }
  else
  {
    return -1;
  }
}

int32_t CKvdb::Put(const char* szKey, const void* szValue, const size_t nValue)
{
  if (NULL == szKey || NULL == szValue)
  {
    return -1;
  }
  leveldb::Status s;
  s = db->Put(write_opt,
              szKey,
              leveldb::Slice((char*)szValue, nValue));
	if(s.ok())
  {
    return 0;
  }
  else
  {
    return -1;
  }
}

int32_t CKvdb::Get(const char* szKey, void* szValue, const size_t nValue)
{
  if(NULL == szKey||NULL == szValue)
  {
    return -1;
  }

  string value;
  leveldb::Status s;
	s = db->Get(read_opt,
              szKey,
              &value);

	if(!s.ok())
  {
    return -1;
  }
  if (nValue < value.size())
  {
    printf("size error!\n");
    return -1;
  }
  memcpy((char*)szValue, value.c_str(), value.size());
  return 0;
}

int32_t CKvdb::Delete(const char* szKey)
{
  if (NULL == szKey)
  {
    return -1;
  }
  leveldb::Status s;
  s = db->Delete(leveldb::WriteOptions(), szKey);
	if(!s.ok())
  {
    return -1;
  }
  return 0;
}
